package com.zhu.blog.controller;



import com.zhu.blog.dao.BlogRepository;
import com.zhu.blog.model.Blog;
import com.zhu.blog.service.BlogService;
import com.zhu.blog.service.TagService;
import com.zhu.blog.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/***
 *博客首页
 */

@Controller
public class IndexController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private TagService tagService;

    @Autowired
    private TypeService typeService;


    @GetMapping("/")
    public String index(@PageableDefault(size = 8,sort = {"updateTime"},direction = Sort.Direction.DESC)
                                    Pageable pageable, Model model){
        //传给页面左边博客展示的内容
        model.addAttribute("page",blogService.listIndexBlog(pageable));
        //传给页面右边types分类的内容
        model.addAttribute("types",typeService.listTypeTop(6));
        //传给页面右边tags标签的内容
        model.addAttribute("tags",tagService.listTagTop(8));
        //传给页面右边推荐的内容
        model.addAttribute("recommendBlogs",blogService.listBlogRecommendTop(6));
        return "index";
    }

    /*退出登录跳转页面*/
    @GetMapping("/index")
    public String index1(@PageableDefault(size = 8,sort = {"updateTime"},direction = Sort.Direction.DESC)
                                     Pageable pageable, Model model,
                         @RequestHeader(value = "User-Agent",required=true) String userAgent){
        model.addAttribute("page",blogService.listIndexBlog(pageable));
        model.addAttribute("types",typeService.listTypeTop(6));
        model.addAttribute("tags",tagService.listTagTop(8));
        model.addAttribute("recommendBlogs",blogService.listBlogRecommendTop(6));
        return "index";
    }

    //搜索的结果展示
    @RequestMapping("/search")
    public String search(@PageableDefault(size = 5,sort = {"updateTime"},direction = Sort.Direction.DESC)
                                 Pageable pageable, @RequestParam(value = "query") String query, Model model){
        //分页显示所查询出来的内容
        model.addAttribute("page",blogService.listBlogQuery("%"+query+"%",pageable));
        //回显给页面所查询的字符串
        model.addAttribute("query",query);
        return "search";
    }

    //博客详情信息
    @GetMapping("/blog/{id}")
    public String blogDetail(@PathVariable Long id, Model model,Blog blog){
        blog.setViews(blogService.updateViews(id));
        model.addAttribute("blog",blogService.getAndConvert(id));
        return "blog";
    }

    //底部跳转到最新发布的博客
    @GetMapping("/footer/newblog")
    public String newblogs(Model model){
        model.addAttribute("newblogs",blogService.listBlogRecommendTop(3));
        return "fragments :: newBlogList";
    }
}
